import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import store from '@/store'
import router from '@/router'
import {serverIp} from '../../public/config'
// create an axios instance
const downService = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    baseURL: serverIp, // url = base url + request url
    responseType: "blob"
})

// request interceptor
downService.interceptors.request.use(
    config => {
        // do something before request is sent

        if (store.getters.token) {
            config.headers['Authorization'] = localStorage.getItem("token")
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)
downService.interceptors.response.use(async (res) => {
    //成功的回调
    if (res.data.code === 999) {
        localStorage.removeItem("token");
        localStorage.removeItem("menuList");
        localStorage.removeItem("userinfo");
        router.push('/login')
        Message({
            message: res.data.msg || 'Error',
            type: 'error',
            duration: 5 * 1000
        })
        router.push('/login')
        return Promise.reject(new Error('请重新登录'))
    } else {
        return res
    }
}, (err) => {
    //失败的回调
    if (err === '未登录') {
        router.push('/login')
    }
    // router.push('/login')

    // return Promise.reject(err)
})

export default downService
